/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controlador.ControlImagen;
import Controlador.ControlProdServ;
import Modelo.Imagen;
import java.awt.Component;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;

/**
 *
 * @author Damian
 */
public class SeleccionarImagen extends javax.swing.JFrame {

    /**
     * Creates new form SeleccionarImagen
     */
    ArrayList<Imagen> l;
    ControlImagen control = new ControlImagen();
    int cod;
    boolean guardar;
    String c;
    public SeleccionarImagen(int cod) {
        initComponents();
        this.cod = cod;
        actualizar();
    }

    public void actualizar() {
        try {
            lista.removeAll();
            lista.setCellRenderer(
                    new DefaultListCellRenderer() {
                        DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();

                        @Override
                        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus
                        ) {
                            Icon theIcon = null;
                            String theText = null;
                            JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
                                    isSelected, cellHasFocus);
                            if (value instanceof Object[]) {
                                Object values[] = (Object[]) value;
                                theIcon = (Icon) values[0];
                                theText = (String) values[1];
                            }
                            if (theIcon != null) {
                                renderer.setIcon(theIcon);
                            }
                            renderer.setText(theText);

                            return renderer;
                        }
                    }
            );
            l = control.getImagenes();
            lista.setModel(new DefaultListModel());
            for (int i = 0; i < l.size(); i++) {
                ((DefaultListModel) lista.getModel()).addElement(new Object[]{new ImageIcon(l.get(i).getImagen()), l.get(i).getNombre()});

            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        btnAgregarImg = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        btnSeleccionar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lista = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Seleccionar Imagen");

        jToolBar1.setRollover(true);

        btnAgregarImg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/list-add.png"))); // NOI18N
        btnAgregarImg.setFocusable(false);
        btnAgregarImg.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAgregarImg.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAgregarImg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarImgActionPerformed(evt);
            }
        });
        jToolBar1.add(btnAgregarImg);

        getContentPane().add(jToolBar1, java.awt.BorderLayout.NORTH);

        btnSeleccionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/dialog-ok-apply (2).png"))); // NOI18N
        btnSeleccionar.setText("Seleccionar");
        btnSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarActionPerformed(evt);
            }
        });
        jPanel1.add(btnSeleccionar);

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/dialog-cancel (2).png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        jPanel1.add(btnCancelar);

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);

        jPanel2.setLayout(new java.awt.BorderLayout(10, 10));

        lista.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lista.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(lista);

        jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jLabel1.setBackground(new java.awt.Color(255, 255, 204));
        jLabel1.setForeground(new java.awt.Color(0, 153, 255));
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/image-x-generic.png"))); // NOI18N
        jLabel1.setText("Seleccione una imagen para el producto.");
        jLabel1.setOpaque(true);
        jPanel2.add(jLabel1, java.awt.BorderLayout.PAGE_START);

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarImgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarImgActionPerformed
        JFileChooser fc = new JFileChooser();
        int opc = fc.showOpenDialog(rootPane);
        if (opc == JFileChooser.APPROVE_OPTION) {
            try {
                control.guardarImagen(fc.getSelectedFile().getPath(),
                        fc.getSelectedFile().getName());
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(rootPane, "Error al insertar la imagen.");
                ex.printStackTrace();
            } catch (FileNotFoundException ex) {
                System.out.println("Archivo no encontrado");
            }
        }
        actualizar();
    }//GEN-LAST:event_btnAgregarImgActionPerformed

    private void btnSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarActionPerformed
        if (lista.getSelectedIndex()>=0) {
            guardar = true;
            //this.notify();
            ControlProdServ con = new ControlProdServ();
            con.agregarImagen(Integer.toString(cod), c);
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Seleccione un elemento de la lista");
        }
    }//GEN-LAST:event_btnSeleccionarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here
        guardar=false;
        
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    @Override
    public void dispose() {
        super.dispose(); //To change body of generated methods, choose Tools | Templates.
    }

    
    private void listaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaMouseClicked
        try {
            c=(l.get(lista.getSelectedIndex()).getCod());
            //System.out.println("c:"+c);
        } catch (NumberFormatException numberFormatException) {
        }
    }//GEN-LAST:event_listaMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SeleccionarImagen.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SeleccionarImagen.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SeleccionarImagen.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SeleccionarImagen.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SeleccionarImagen(-1).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregarImg;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnSeleccionar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JList lista;
    // End of variables declaration//GEN-END:variables

}
